package com.pxst.fi.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Maps;
import com.pxst.constants.ConfigRedis;
import com.pxst.exception.ParamException;
import com.pxst.fi.req.SendPayInfoReq;
import com.pxst.fi.service.FiService;
import com.pxst.fi.utils.AESUtil;
import com.pxst.merchant.entity.SysMerchantInfoEntity;
import com.pxst.merchant.entity.SysMerchantWhiteListEntity;
import com.pxst.merchant.service.SysMerchantInfoService;
import com.pxst.merchant.service.SysMerchantWhiteListService;
import com.pxst.utils.HttpUtil;
import com.pxst.utils.RedisUtils;

/**
 * @author yangxy
 * @version 创建时间：2023年9月6日 上午10:49:09
 */
@Service
public class FiServiceImpl implements FiService {
	@Autowired
	private SysMerchantInfoService sysMerchantInfoService;
	@Autowired
	private SysMerchantWhiteListService sysMerchantWhiteListService;
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private HttpUtil httpUtil;
	@Value("${http.pxst_amdin.url}")
	private String amdinUrl;

	@Override
	public Map<String,Object> sendPay(String merchant, String ciphertext, HttpServletRequest request) {
		// TODO Auto-generated method stub
		Long merchantId = Long.parseLong(merchant.split("-")[0]);
		SysMerchantInfoEntity sysMerchantInfoEntity = sysMerchantInfoService.getById(merchantId);
		if (ObjectUtils.isEmpty(sysMerchantInfoEntity)) {
			throw new ParamException("商户不存在","422");
		}
		String decrypt = AESUtil.decrypt(ciphertext, sysMerchantInfoEntity.getSecret());
		JSONObject jsonObject = JSON.parseObject(decrypt);
		SendPayInfoReq sendPayInfoReq = JSONObject.toJavaObject(jsonObject, SendPayInfoReq.class);
		if (StringUtils.isEmpty(sendPayInfoReq.getSh_order_no())) {
			throw new ParamException("订单号不能为空","422");
		}
		if (ObjectUtils.isEmpty(sendPayInfoReq.getOrder_amount())) {
			throw new ParamException("提交金额不能为空","422");
		}
		if (sendPayInfoReq.getOrder_amount().compareTo(new BigDecimal(0.00)) <= 0) {
			throw new ParamException("提交金额必须大于0","422");
		}
		//todo 校验金额小数位数
		if (StringUtils.isEmpty(sendPayInfoReq.getOrder_type())) {
			throw new ParamException("充值类型不能为空","422");
		}
		String key = ConfigRedis.CONFIG_REDIS_PREFIX + "TXN_MODE_DESC";
		Object object = redisUtils.get(key);
		// todo 校验充值类型是否在object中
		if(sendPayInfoReq.getBank_code().equals("100") && StringUtils.isEmpty(sendPayInfoReq.getBank_code())) {
			throw new ParamException("银行代码不能为空","422");
		}
		String ip = getIp(request);
		List<SysMerchantWhiteListEntity> list = sysMerchantWhiteListService.list(new LambdaQueryWrapper<SysMerchantWhiteListEntity>()
				.eq(SysMerchantWhiteListEntity::getMerchantId, merchantId).eq(SysMerchantWhiteListEntity::getIp, ip)
				.eq(SysMerchantWhiteListEntity::getStatus, 1).eq(SysMerchantWhiteListEntity::getType, 1));
		if(list.isEmpty()) {
			throw new ParamException(String.format("ip:%s 白名单校验错误", ip),"403");
		}

		Map<String,Object> paramMap = Maps.newHashMap();
		paramMap.put("merchantId", merchantId);
		paramMap.put("order_type", sendPayInfoReq.getOrder_type());
		paramMap.put("request_amount", sendPayInfoReq.getOrder_amount().divide(BigDecimal.valueOf(1000), 6, BigDecimal.ROUND_DOWN));//根据币种配置判断是否需要除以1000并保留6位小数
		paramMap.put("reference", sendPayInfoReq.getSh_order_no());
		paramMap.put("from_bank", sendPayInfoReq.getBank_code());
		paramMap.put("notify_url", sendPayInfoReq.getNotify_url());
		paramMap.put("note", sendPayInfoReq.getNote());
		// todo 调用主后台充值接口
//		ResponseEntity<String> responseEntity = httpUtil.doJsonPost(amdinUrl, JSON.toJSONString(paramMap));
//		if(responseEntity.getStatusCodeValue() != HttpStatus.OK.value()) {
//			// todo 接口调用错误
//		}
//		
//		JSONObject parseObject = JSON.parseObject(responseEntity.getBody());
//		ApiResp apiResp = JSON.toJavaObject(jsonObject, ApiResp.class);
//		if(apiResp.getResCode().equals(ResCodeContants.SUCESS)) {
//			// todo 接口调用错误
//		}
		
		Map<String,Object> reMap = Maps.newHashMap();
		reMap.put("error_code", "200");
		reMap.put("order_id", reMap);
		reMap.put("url", reMap);
		reMap.put("token", reMap);
		reMap.put("order_amount", reMap);
		reMap.put("request_amount", reMap);
		reMap.put("sh_order_no", reMap);
		reMap.put("", reMap);
		reMap.put("", reMap);
		return reMap;
	}

	public String getIp(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip != null) {
			if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
				int index = ip.indexOf(",");
				if (index != -1) {
					return ip.substring(0, index);
				} else {
					return ip;
				}
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (ip != null) {
			if (!ip.isEmpty() && !"unKnown".equalsIgnoreCase(ip)) {
				return ip;
			}
		}
		return request.getRemoteAddr();
	}

}
